package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;

import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityCallNumberBinding;

public class CallNumberActivity extends BaseAc<ActivityCallNumberBinding> {

    private int min = 1, max = 50;
    private int selNum;
    private boolean isStart;

    private Handler mHandler;
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            Random random = new Random();
            selNum = random.nextInt(max - min + 1) + min;
            mDataBinding.tvCallNumber.setText(String.valueOf(selNum));
            mHandler.postDelayed(this, 100);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_call_number;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCallNumberBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivStart.setOnClickListener(this);

        mHandler = new Handler();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivStart://开始
                String minNum = mDataBinding.etMin.getText().toString().trim();
                String maxNum = mDataBinding.etMax.getText().toString().trim();
                min = Integer.parseInt(minNum);
                max = Integer.parseInt(maxNum);
                if (TextUtils.isEmpty(minNum) || TextUtils.isEmpty(maxNum)) {
                    ToastUtils.showShort(getString(R.string.please_input));
                    return;
                }
                if (isStart) {
                    isStart = false;
                    stopTime();
                    mDataBinding.ivStart.setImageResource(R.drawable.ks);
                } else {
                    isStart = true;
                    startTime();
                    mDataBinding.ivStart.setImageResource(R.drawable.tz);
                    mDataBinding.tvCallNumber.setTextColor(Color.parseColor("#BB7125"));
                    mDataBinding.tvCallNumber.setTextSize(52);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.etMin.setText(String.valueOf(min));
        mDataBinding.etMax.setText(String.valueOf(max));
        mDataBinding.tvCallNumber.setText(getString(R.string.please_click_start));
    }

    private void startTime() {
        mHandler.post(mRunnable);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mRunnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTime();
    }

}